import React, { useState, useEffect } from 'react';
import {
  DownSquareOutlined,
  UpSquareOutlined,
  // @ts-ignore
} from '#/utils/antdIcons';
import {
  Drawer,
  Timeline,
  // Form,
  Spin,
  Button,
  Form,
  Tooltip,
  message,
} from 'antd';
import previewIcon from '@/assets/img/preview_icon.png';
import { TjStation } from '@/pages/ETrade/components';
import { HttpCode } from '#/utils/contacts.js';
import InfiniteScroll from 'react-infinite-scroller';
import { AntdBaseTable } from '@/base/TBaseTable';
// @ts-ignore
import { TRCheckboxModal } from '@/components/index.js';
import styles from './index.less';
import { getPlanLogList } from '../../../services';
import moment from 'moment';
import { OPERATE_TYPE } from '../../../dictionary';
import type {
  IDealElementOptions,
  IFindOperationLogDataType,
  IStationsDataType,
} from '../../../type';
import { TRDefault } from '@/components/index.js';

interface IProps {
  /**
   * 是否显示操作日志
   */
  visible: boolean;
  /**
   * 关闭操作日志
   */
  onClose: () => void;
  /**
   * 全部交易单元
   */
  allStationData?: IStationsDataType;
}
const OperationLog = (props: IProps) => {
  const { visible, onClose, allStationData } = props;
  const [form] = Form.useForm();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<boolean>(false);
  const [logData, setLogData] = useState<any>({});
  const [hasMore, setHasMore] = useState(true);
  const [currentData, setCurrentData] = useState<any>([]);
  const [count, setCount] = useState<number>(1);

  const handleCancel = async () => {
    onClose();
    form.resetFields();
  };

  const initFetchTimeLog = async (params: any, isAdd?: boolean) => {
    setIsLoading(true);
    const response = await getPlanLogList(params);
    if (response && response.statusCode === HttpCode.SUCCESS) {
      setIsLoading(false);
      const data = response?.planLogBodyPage || [];
      setLogData(data);
      const data1 = (data?.records || []).map((item: IFindOperationLogDataType) => ({
        ...item,
      }));
      if (isAdd) {
        setCount(params.current);
        setCurrentData([...currentData, ...data1]);
        setHasMore(data.total > 50 * params.current ? true : false);
      } else {
        setHasMore(data.total > 50 ? true : false);
        setCount(1);
        setCurrentData(data1);
      }
      setError(false);
    } else {
      setIsLoading(false);
      setError(true);
      message.error(response?.message || '错误请求');
    }
  };

  const loadMore = () => {
    if (!hasMore) return;
    const current = count + 1;
    const params = {
      stationId: form.getFieldValue('stationIdList'),
      current,
    };
    initFetchTimeLog(params, true);
  };

  const onSpread = (record: IFindOperationLogDataType) => {
    let _currentData: any = [...currentData];
    _currentData = _currentData.map((item: { logId: number; isSpread: any }) => {
      return {
        ...item,
        isSpread: item.logId === record.logId ? !item.isSpread : item?.isSpread,
      };
    });
    setCurrentData(_currentData);
  };

  const onFinish = (value: any) => {
    const params = {
      stationId: value.stationIdList,
      current: 1,
    };
    initFetchTimeLog(params);
  };

  const columns: any = [
    {
      name: '起始时间',
      width: '120px',
      align: 'center',
      height: '28px',
      code: 'startDate',
      render: (v: any) => {
        return <div className={styles.date}>{v}</div>;
      },
    },
    {
      name: '终止时间',
      width: '120px',
      align: 'center',
      height: '28px',
      code: 'endDate',
      render: (v: any) => {
        return <div className={styles.date}>{v}</div>;
      },
    },
    {
      name: '影响容量',
      width: '110px',
      align: 'center',
      height: '28px',
      code: 'effectCapacity',
    },
    {
      name: '检修事件',
      width: '180px',
      align: 'center',
      height: '28px',
      code: 'tendingEvent',
      render(v: string) {
        return (
          // @ts-ignore
          <Tooltip title={v} getPopupContainer={(triggerNode) => triggerNode.parentNode}>
            <div className={styles.ellipsis}>{v || '-'}</div>
          </Tooltip>
        );
      },
    },
  ];

  useEffect(() => {
    if (visible) {
      const params = {
        stationId: (allStationData?.dealElementOptions || []).map(
          (item: IDealElementOptions) => item?.value || '',
        ),
        current: 1,
      };
      initFetchTimeLog(params);
    }
  }, [visible]);

  useEffect(() => {
    setCount(1);
    setHasMore(true);
  }, []);

  const getStatus = (state: number) => {
    if (state === 0) {
      return <span className={styles.noSp}>未开始</span>;
    }
    if (state === 1) {
      return <span className={styles.falSp}>已取消</span>;
    }
    if (state === 2) {
      return <span className={styles.rigSp}>已完成</span>;
    }
  };

  const renderItem = (item: any) => (
    <Timeline.Item key={item.logId}>
      <div className={styles.timelineItem}>
        <div className={styles.header}>
          <div className={styles.title}>
            <div className={styles.date}>
              {moment(item.createTime).format('YYYY.MM.DD HH:mm:ss')}
            </div>
            <div className={styles.type}>
              {item.stationName +
                ' ' +
                OPERATE_TYPE[item.operateType] +
                `检修计划${item.operateType === 2 ? '状态' : ''}`}
            </div>
            <div className={styles.spread} onClick={() => onSpread(item)}>
              {item?.isSpread ? (
                <UpSquareOutlined className={styles.spreadLogo} />
              ) : (
                <DownSquareOutlined className={styles.spreadLogo} />
              )}
            </div>
          </div>
          <div className={styles.updateUser}>操作人：{item.tendingUserName}</div>
        </div>

        {item.isSpread && (
          <>
            {item.operateType === 2 ? (
              <div style={{ margin: '10px 0' }}>
                <span style={{ marginRight: '8px' }}>调整计划状态为</span>
                {getStatus(item.planState)}
              </div>
            ) : null}
            <div className={styles.antdBaseTable}>
              <AntdBaseTable
                dataSource={[item] || []}
                columns={columns as any}
                style={{
                  '--row-height': '28px',
                  // '--header-bgcolor': '#383C3E',
                  '--header-row-height': '28px',
                  '--cell-padding': '4px 16px',
                  '--cell-border-vertical': '1px solid #4E5154',
                  '--header-cell-border-vertical': '1px solid #4E5154',
                  '--hover-bgcolor': '#222629',
                  '--bgcolor': '#222629',
                }}
              />
            </div>
          </>
        )}
      </div>
    </Timeline.Item>
  );
  return (
    <Drawer
      width={642}
      className={styles.operateLog}
      visible={visible}
      onClose={handleCancel}
      title={
        <div className={styles.titleDiv}>
          <img src={previewIcon} className={styles.titleLogo} />
          <span className={styles.title}>操作日志</span>
        </div>
      }
      footer={null}
      destroyOnClose={true}
    >
      <Form
        form={form}
        name="filter"
        requiredMark={false}
        colon={false}
        autoComplete="off"
        onFinish={onFinish}
      >
        <Form.Item
          name="stationIdList"
          rules={[{ required: true, message: '请选择交易单元' }]}
          initialValue={allStationData?.allKeys || []}
        >
          <TjStation
            style={{ width: 200 }}
            options={allStationData?.dealElementModalOptions || []}
          />
        </Form.Item>
        <Button type="primary" htmlType="submit" className={styles.searchBtn}>
          查询
        </Button>
      </Form>
      <div className={styles.container}>
        {error ? (
          <TRDefault type={'emptysm'} message={'系统异常'} />
        ) : logData?.records && logData?.records.length ? (
          <Spin spinning={isLoading} className={styles.spinloading}>
            <div className={styles.content}>
              <InfiniteScroll
                initialLoad={false}
                pageStart={0}
                loadMore={loadMore}
                hasMore={!isLoading && hasMore}
                useWindow={false}
                className={styles.infiniteScroll}
              >
                <Timeline>{currentData.map((item: any) => renderItem(item))}</Timeline>
                {/* {!hasMore && data.length !== 0 && (
                  <div className={styles.loader} key={0}>
                    已经到底了～
                  </div>
                )} */}
              </InfiniteScroll>
            </div>
          </Spin>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </Drawer>
  );
};

export default OperationLog;
